package com.flute.tools.xml.xpath;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import com.flute.tools.xml.XmlNode;

public class SplitedMultiPathParser implements IMultiPathParser {

	@Override
	public void parse(PathValuePair[] pairs, XmlNode parent) {
		if (pairs != null && pairs.length > 0) {
			if (pairs[0].getPathNode() instanceof SplitedGroupPathNode) {
				SplitedGroupPathNode node = (SplitedGroupPathNode) pairs[0]
						.getPathNode();
				XmlNode group = PathParsers.getInstance().parse(
						node.getGroup(), null, parent);

				HashMap<IPathNode, List<String>> map = new HashMap<IPathNode, List<String>>();
				int minSize = 1000000;
				for (PathValuePair pair : pairs) {
					List<String> values = new ArrayList<String>();
					if (pair.getValue() != null) {
						values.addAll(Arrays.asList(pair.getValue().split(
								node.getSpliter())));
					}
					if (values.size() < minSize) {
						minSize = values.size();
					}
					map.put(((SplitedGroupPathNode) pair.getPathNode())
							.getPathNode(), values);
				}

				for (int i = 0; i < minSize; i++) {
					XmlNode innerGroup = PathParsers.getInstance().parse(
							node.getInnerGroup(), null, group);
					for (IPathNode pn : map.keySet()) {
						PathParsers.getInstance().parse(pn, map.get(pn).get(i),
								innerGroup);
					}
				}
			}
		}
	}
}
